package com.wit.example.fragment;

import android.graphics.Color;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.wit.example.R;
import com.wit.example.share.SharedViewModel;
import com.wit.example.util.DataExtractor;

import java.util.Arrays;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link DiscoverFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class DiscoverFragment extends Fragment {

    // fragment之间共享数据
    private SharedViewModel viewModel;



    // 画图用的表格
    // private LineChart chart;

    private LineChart chartAcceleration;
    private LineChart chartAngle;
    private LineChart chartMagneticField;


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private String username;

    public DiscoverFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment DiscoverFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static DiscoverFragment newInstance(String param1, String param2) {
        DiscoverFragment fragment = new DiscoverFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
            username = getArguments().getString("USERNAME_KEY");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_discover, container, false);

        chartAcceleration = view.findViewById(R.id.chart_acceleration);
        chartAngle = view.findViewById(R.id.chart_angle);
        chartMagneticField = view.findViewById(R.id.chart_magnetic_field);

//        chart = view.findViewById(R.id.chart1);

        return view;

        // return inflater.inflate(R.layout.fragment_discover, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        super.onViewCreated(view, savedInstanceState);
        initChart(chartAcceleration);
        initChart(chartAngle);
        initChart(chartMagneticField);


        viewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
        // 观察 ViewModel 中的数据变化
//        viewModel.getDataArray().observe(getViewLifecycleOwner(), new Observer<float[]>() {
//            @Override
//            public void onChanged(float[] dataArray) {
//                // 在这里处理接收到的数组数据
//                if(dataArray != null) {
//                    addEntry(dataArray[0],dataArray[1],dataArray[2]);
//                }
//            }
//        });

        // 观察 ViewModel 中的数据变化并更新 UI
        viewModel.getDataString().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(String dataString) {
                if(dataString != null) {
                    float[] accelerations = DataExtractor.extractAcceleration(dataString);
                    float[] angles = DataExtractor.extractAngles(dataString);
                    float[] magneticFields = DataExtractor.extractMagneticFields(dataString);
                    if(accelerations != null && angles != null && magneticFields != null){
                        addEntry(chartAcceleration,accelerations[0],accelerations[1],accelerations[2]);
                        addEntry(chartAngle,angles[0],angles[1],angles[2]);
                        addEntry(chartMagneticField,magneticFields[0],magneticFields[1],magneticFields[2]);
                    }
                }
            }
        });


    }

    private void initChart(LineChart chart) {
        // 初始化折线图
        chart.getDescription().setEnabled(false);
        chart.setTouchEnabled(true);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setPinchZoom(true);

        // 空数据
        LineData data = new LineData();
        data.setValueTextColor(Color.WHITE);

        // 添加到图表
        chart.setData(data);
    }



    private void addEntry(LineChart chart,float yValueX, float yValueY, float yValueZ) {
        LineData data = chart.getData();

        if (data != null) {
            LineDataSet setX = (LineDataSet) data.getDataSetByIndex(0);
            LineDataSet setY = (LineDataSet) data.getDataSetByIndex(1);
            LineDataSet setZ = (LineDataSet) data.getDataSetByIndex(2);

            if (setX == null) {
                setX = createSet("X", Color.RED);
                data.addDataSet(setX);
            }
            if (setY == null) {
                setY = createSet("Y", Color.GREEN);
                data.addDataSet(setY);
            }
            if (setZ == null) {
                setZ = createSet("Z", Color.BLUE);
                data.addDataSet(setZ);
            }

            // 添加新的值
            data.addEntry(new Entry(setX.getEntryCount(), yValueX), 0);
            data.addEntry(new Entry(setY.getEntryCount(), yValueY), 1);
            data.addEntry(new Entry(setZ.getEntryCount(), yValueZ), 2);

            data.notifyDataChanged();
            chart.notifyDataSetChanged();
            chart.setVisibleXRangeMaximum(50);
            chart.moveViewToX(data.getEntryCount());
        }
    }

    private LineDataSet createSet(String label, int color) {
        LineDataSet set = new LineDataSet(null, label);
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setColor(color);
        set.setLineWidth(2f);
        set.setFillAlpha(65);
        set.setFillColor(color);
        set.setHighLightColor(Color.rgb(244, 117, 117));
        set.setValueTextColor(Color.WHITE);
        set.setValueTextSize(9f);
        set.setDrawValues(false);
        return set;
    }


}
